<?php

    $rootDir = $_SERVER['DOCUMENT_ROOT'];

    require_once($rootDir.'/classes/SessionManager.class.php');
    require_once($rootDir.'/classes/db/SQLiteConnector.class.php');
    require_once($rootDir.'/classes/Card.class.php');
    require_once($rootDir.'/classes/LeproUser.class.php');   
    require_once($rootDir.'/classes/db/LeproUserDAO.class.php');
    require_once($rootDir.'/classes/LeproBJGroup.class.php');   
    require_once($rootDir.'/classes/db/LeproBJGroupDAO.class.php');
    require_once($rootDir.'/functions.php');
    
    // $userDAO->getIdsNamesPairs(true, userIdConvertor)     
    
    date_default_timezone_set('Europe/Moscow');
        
    $target = urldecode($_POST['target']);
    $userId = urldecode($_POST['userId']);
    $rows = urldecode($_POST['rows']);
    $offset = urldecode($_POST['offset']);
    $orderBy = urldecode($_POST['oby']);
    $orderAsc = urldecode($_POST['oasc']);
    
    if ((preg_match("/^(user|users|groups)$/", $target) > 0) &&
        ((strlen($userId) == 0) || (preg_match("/^\d*$/", $userId) > 0)) &&
        (preg_match("/^\d*$/", $rows) > 0) &&
        (preg_match("/^-?\d*$/", $offset) > 0) &&
        (preg_match("/^[A-Za-z]*$/", $orderBy) > 0) &&
        (preg_match("/^(true|false)$/", $orderAsc) > 0)) {
        $connector = SQLiteConnector::getInstance();                
        if ($connector->connect()) { // connect to DB
            $userDAO = new LeproUserDAO($connector->getDB());
            $groupDAO = new LeproBJGroupDAO($connector->getDB());
            $result = ':(';
            switch ($target) {
                case 'user': {
                    if (SessionManager::isUserChecked($userId)) {                         
                        $user = $userDAO->load($userId);
                        if ($user != null) {
                            $groups = $groupDAO->getAll($rows, $offset, $orderBy, $orderAsc == 'true', $user->getGroupsIDs());
                            $groupsArr = array();
                            foreach ($groups as $groupId => $group) {
                                $groupInfo = $group->getSummary();
                                //var_dump($groupInfo); 
                                $groupInfo['ctime'] = format_time($groupInfo['ctime']);
                                $groupUsers = array();
                                if (not_empty($groupInfo['users'])) {
                                    foreach($groupInfo['users'] as $guserId) {
                                        $groupUser = $userDAO->load($guserId);
                                        if ($groupUser != null) {
                                            $userInfo = $groupUser->getSummary();
                                            $userInfo['uid'] = userIdConvertor($userInfo['uid']);
                                            $userInfo['rtime'] = format_time($userInfo['rtime']);
                                            $userInfo['card'] = Card::getCardSummary($userInfo['card']);
                                            if ($guserId == $groupInfo['creator']) $groupInfo['creator'] = $userInfo['uname']; 
                                            $groupUsers[] = $userInfo;
                                        }                         
                                    }
                                }
                                $groupInfo['ajoin'] = false;
                                $groupInfo['aleave'] = true;
                                $groupInfo['users'] = $groupUsers;
                                //var_dump($groupInfo);                        
                                $groupsArr[] = $groupInfo;
                            } 
                            $result = array(
                                "count" => count($user->getGroupsIDs()), 
                                "groups" => $groupsArr);
                        }
                    } else $result = ':('; 
                } break;
                case 'users': {
                    $usersCount = $userDAO->getCount();
                    $users = $userDAO->getAll($rows, $offset, $orderBy, $orderAsc == 'true');
                    $usersArr = array();                    
                    foreach ($users as $userId => $user) {
                        $userInfo = $user->getSummary();
                        //var_dump($groupInfo); 
                        $userInfo['uid'] = userIdConvertor($userInfo['uid']);
                        $userInfo['rtime'] = format_time($userInfo['rtime']);
                        $userInfo['card'] = Card::getCardSummary($userInfo['card']);
                        $userGroups = array();
                        if (not_empty($userInfo['groups'])) {
                            foreach($userInfo['groups'] as $groupId) {
                                $userGroup = $groupDAO->load($groupId);
                                if ($userGroup != null) {
                                    $groupInfo = $userGroup->getSummary();
                                    $groupInfo['ctime'] = format_time($groupInfo['ctime']);
                                    $groupInfo['scoredata'] = Card::getCardsScoreSumSummary($userDAO->getUsersAndCards($groupInfo['users']));
                                    $groupInfo['users'] = $userDAO->getUsersNames($groupInfo['users']);
                                    $groupInfo['creator'] = (count($groupInfo['users']) > 0) ? $groupInfo['users'][0] : '';                                    
                                    // if ($userId == $groupInfo['creator']) $groupInfo['creator'] = $userInfo['uname']; 
                                    $userGroups[] = $groupInfo;
                                }                         
                            }
                        }
                        $userInfo['groups'] = $userGroups;                        
                        $usersArr[] = $userInfo;
                    } 
                    $result = array(
                        "count" => $usersCount, 
                        "users" => $usersArr);
                } break;
                case 'groups': {
                    $groupsCount = $groupDAO->getCount();
                    $groups = $groupDAO->getAll($rows, $offset, $orderBy, $orderAsc == 'true');
                    $groupsArr = array();
                    foreach ($groups as $groupId => $group) {
                        $groupInfo = $group->getSummary();
                        //var_dump($groupInfo);                         
                        $groupInfo['ctime'] = format_time($groupInfo['ctime']);
                        $groupUsers = array();
                        if (not_empty($groupInfo['users'])) {
                            $scoreData = Card::getCardsScoreSumSummary($userDAO->getUsersAndCards($groupInfo['users']));
                            foreach($groupInfo['users'] as $guserId) {
                                $groupUser = $userDAO->load($guserId);
                                if ($groupUser != null) {
                                    $userInfo = $groupUser->getSummary();
                                    $userInfo['uid'] = userIdConvertor($userInfo['uid']);
                                    $userInfo['rtime'] = format_time($userInfo['rtime']);
                                    $userInfo['card'] = Card::getCardSummary($userInfo['card']);
                                    $userInfo['card']['score'] = $scoreData["scores"][$guserId];
                                    if ($guserId == $groupInfo['creator']) $groupInfo['creator'] = $userInfo['uname']; 
                                    $groupUsers[] = $userInfo;
                                }                         
                            }
                            //$groupInfo['scoredata'] = $scoreData; 
                        }
                        $userInGroup = $group->haveUser($userId);
                        //echo $group->getID().'>'.$userId.':'.$userInGroup.'.';
                        $groupInfo['ajoin'] = !$userInGroup;
                        $groupInfo['aleave'] = $userInGroup;
                        $groupInfo['users'] = $groupUsers;
                        //var_dump($groupInfo);                        
                        $groupsArr[] = $groupInfo;
                    } 
                    $result = array(
                        "count" => $groupsCount, 
                        "groups" => $groupsArr);
                } break;                                
            }
            echobig(json_encode($result));
        } else echo ':(';        
    } else echo ':('; 
      
?>
